namespace UniversalAdminSystem.Infrastructure.Services;

public class FileScaner
{
    public static IEnumerable<FileSystemInfo> ScanDirectory(string path, string searchPattern)
    {
        var fileSystemInfos = new List<FileSystemInfo>();
        if (!Directory.Exists(path)) throw new DirectoryNotFoundException($"目录不存在: {path}");
        try
        {
            ScanInternal(path, searchPattern, fileSystemInfos);
        }
        catch (UnauthorizedAccessException)
        {
            throw new UnauthorizedAccessException($"无权限访问: {path}");
        }
        return fileSystemInfos;
    }

    private static void ScanInternal(string path, string searchPattern, List<FileSystemInfo> fileSystemInfos)
    {
        var directoryInfo = new DirectoryInfo(path);
        fileSystemInfos.Add(directoryInfo);
        var files = directoryInfo.GetFiles(searchPattern);
        fileSystemInfos.AddRange(files);
        foreach (var subDirectory in directoryInfo.GetDirectories(searchPattern))
        {
            try
            {
                ScanInternal(subDirectory.FullName, searchPattern, fileSystemInfos);
            }
            catch (UnauthorizedAccessException)
            {
                continue;
            }
        }
    }
}